package com.tronsis.distribution.activity.me;

import android.os.Bundle;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.google.gson.internal.LinkedTreeMap;
import com.tronsis.distribution.R;
import com.tronsis.distribution.SysApplication;
import com.tronsis.distribution.activity.MainActivity;
import com.tronsis.distribution.bean.ProductDetailBean;
import com.tronsis.distribution.bean.RegionBean;
import com.tronsis.distribution.bean.ScanDeliveryReq;
import com.tronsis.distribution.bean.UserBean;
import com.tronsis.distribution.biz.factory.CommonFactory;
import com.tronsis.distribution.biz.factory.OrderBizFactory;
import com.tronsis.distribution.util.CommonUtil;
import com.tronsis.distribution.util.StateUtil;
import com.tronsis.distribution.widget.address.BottomDialog;
import com.tronsis.distribution.widget.address.OnAddressSelectedListener;
import com.tronsis.library.activity.ToolBarBaseActivity;
import com.tronsis.library.http.UICallBack;
import com.tronsis.library.util.IntentUtil;
import com.tronsis.library.util.KeyboardUtils;
import com.tronsis.library.util.ToastUtil;

import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

public class DeliverInfoEditActivity extends ToolBarBaseActivity {

    @BindView(R.id.tv_role)
    TextView mTvRole;
    @BindView(R.id.tv_level)
    TextView mTvLevel;
    @BindView(R.id.tv_region)
    TextView mTvRegion;
    @BindView(R.id.ll_user_info)
    LinearLayout mLlUserInfo;
    @BindView(R.id.btn_confirm)
    Button mBtnConfirm;
    @BindView(R.id.et_phone)
    EditText mEtPhone;
    @BindView(R.id.et_name)
    EditText mEtName;
    @BindView(R.id.tv_province)
    TextView mTvProvince;
    @BindView(R.id.ll_province)
    LinearLayout mLlProvince;
    @BindView(R.id.tv_address_area)
    TextView mTvArea;
    @BindView(R.id.ll_address)
    LinearLayout mLlAddress;
    @BindView(R.id.et_detail)
    EditText mEtDetail;
    @BindView(R.id.ll_address_detail)
    LinearLayout mLlAddressDetail;

    private RegionBean mProvinceRegionBean;
    private RegionBean mSelectRegionBean;
    private List<RegionBean> mRegionBeanList;
    private String mReceiverId;
    private ProductDetailBean mProductDetailBean;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_deliver_info_edit);
        ButterKnife.bind(this);
        setTitle(true, getString(R.string.deliver_info_edit));

        mProductDetailBean = (ProductDetailBean) getIntent().getSerializableExtra("ProductDetailBean");


        mRegionBeanList = SysApplication.getRegionList();


        initView();
    }

    private void initView() {
        mEtPhone.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                if (mEtPhone.getText().toString().length() > 10) {
                    httpFindUser(mEtPhone.getText().toString());
                } else {
                    setEmpty();
                }

            }

            @Override
            public void afterTextChanged(Editable s) {

            }
        });
    }

    private void setEmpty() {
        mLlUserInfo.setVisibility(View.GONE);
        mEtName.setText("");
        mReceiverId = null;
    }

    @OnClick(R.id.btn_confirm)
    void confirmClick() {
        String detail = mEtDetail.getText().toString();
        String name = mEtName.getText().toString();
        String phone = mEtPhone.getText().toString();
        String province = mTvProvince.getText().toString();
        String region = mTvArea.getText().toString();

        if (TextUtils.isEmpty(phone)) {
            ToastUtil.showMessage(mContext, "请输入手机号");
            return;
        }

        if (TextUtils.isEmpty(name)) {
            ToastUtil.showMessage(mContext, "请输入收货人");
            return;
        }

        if (TextUtils.isEmpty(province)) {
            ToastUtil.showMessage(mContext, "请输入所属省份");
            return;
        }

        if (TextUtils.isEmpty(region)) {
            ToastUtil.showMessage(mContext, "请输入所属城市");
            return;
        }

        if (TextUtils.isEmpty(detail)) {
            ToastUtil.showMessage(mContext, "请输入详细地址");
            return;
        }
        LinkedTreeMap<String, String> map = new LinkedTreeMap<>();
        map.put(mProductDetailBean.getQrCode(), mProductDetailBean.getId());


        String regionCode = mSelectRegionBean.getCode().substring(0, 6);
        ScanDeliveryReq.ReceiverAddrBean receiverAddrBean = new ScanDeliveryReq.ReceiverAddrBean();
        receiverAddrBean.setName(name);
        receiverAddrBean.setPhone(phone);
        receiverAddrBean.setRegion(regionCode);
        receiverAddrBean.setDetail(detail);

        ScanDeliveryReq req = new ScanDeliveryReq();
        req.setCodeIds(map);
        req.setName(name);
        req.setPhone(phone);
        req.setReceiverId(mReceiverId);
        req.setReceiverAddr(receiverAddrBean);

        httpDeliveryScan(req);
    }

    @OnClick(R.id.ll_province)
    public void provinceClick() {
        KeyboardUtils.hideSoftInput(this);
        final RegionBean regionBean = new RegionBean();
        regionBean.setChildren(mRegionBeanList);
        final BottomDialog dialog = new BottomDialog(this, regionBean, 1);
        dialog.setOnAddressSelectedListener(new OnAddressSelectedListener() {
            @Override
            public void onAddressSelected(RegionBean province, RegionBean city, RegionBean county, RegionBean street) {
                String s = (province == null ? "" : "" + province.getName()) + (city == null ? "" : "" + city.getName());

                if (mProvinceRegionBean != null && !mProvinceRegionBean.getCode().equals(province.getCode())) {
                    mTvArea.setText(null);
                }
                mProvinceRegionBean = province;
                mTvProvince.setText(mProvinceRegionBean.getName());

                dialog.dismiss();


            }
        });
        dialog.show();
        dialog.getCloseBtn().setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                dialog.dismiss();
            }
        });
    }

    /**
     * 弹出地区选择框
     */
    @OnClick(R.id.ll_address)
    public void addressClick() {
        KeyboardUtils.hideSoftInput(this);
        if (mProvinceRegionBean == null) {
            ToastUtil.showMessage(this, "请先选择所属省份");
            return;
        }

        final BottomDialog dialog = new BottomDialog(this, mProvinceRegionBean, 2);
        dialog.setOnAddressSelectedListener(new OnAddressSelectedListener() {
            @Override
            public void onAddressSelected(RegionBean province, RegionBean city, RegionBean county, RegionBean street) {
                //(province == null ? "" : province.getName()) +
                String s = (province == null ? "" : "" + province.getName()) + (city == null ? "" : "" + city.getName());
                mTvArea.setText(s);
                mSelectRegionBean = city;
                dialog.dismiss();
            }
        });
        dialog.show();
        dialog.getCloseBtn().setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                dialog.dismiss();
            }
        });
    }


    private void httpFindUser(String phone) {
        try {
            CommonFactory.createBiz().findUser(this, phone, new UICallBack() {
                @Override
                public void onStart() {

                }

                @Override
                public void onRefresh(Object data) {
                    UserBean userBean = (UserBean) data;
                    if (userBean != null) {
                        mLlUserInfo.setVisibility(View.VISIBLE);
                        mEtName.setText(userBean.getName());
                        mTvRole.setText("代理角色：" + StateUtil.getRoleString(mContext, userBean.getRole()));
                        mTvLevel.setText("代理等级：" + StateUtil.getLevelText(userBean.getLevel(),userBean.isUnited()));
                        mTvRegion.setText(("归属地：" + CommonUtil.getRegionString(userBean.getRegion())));
                        mReceiverId=userBean.getId();
                    } else {
                        setEmpty();
                    }
                }

                @Override
                public void onFailure(int status) {
                    setEmpty();

                }
            });
        } catch (Exception e) {
            setEmpty();
            e.printStackTrace();
        }
    }


    private void httpDeliveryScan(ScanDeliveryReq scanDeliveryReq) {
        try {
            OrderBizFactory.createBiz().qrScanDelivery(this, scanDeliveryReq, new UICallBack() {
                @Override
                public void onStart() {
                    showLoadingDialog();
                }

                @Override
                public void onRefresh(Object data) {
                    dismissLoadingDialog();
                    ToastUtil.showMessage(mContext,"发货成功");
                    IntentUtil.goBackToActivity(DeliverInfoEditActivity.this, MainActivity.class);
                    finish();
                }

                @Override
                public void onFailure(int status) {
                    dismissLoadingDialog();
                }
            });
        } catch (Exception e) {
            dismissLoadingDialog();
            e.printStackTrace();
        }
    }
}
